#!/bin/bash

# 定义日志文件路径
LOG_FILE="/var/log/docker_install.log"

# 定义日志记录函数
function logger() {
    local log_level="$1"
    local message="$2"
    local color_code=""

    case "$log_level" in
    "error" | "red")
        color_code="\e[1;31m"
        ;;
    "warning" | "yellow")
        color_code="\e[1;33m"
        ;;
    "success" | "green")
        color_code="\e[1;32m"
        ;;
    "info" | "blue")
        color_code="\e[1;34m"
        ;;
    esac

    echo -e "${color_code}${message}\e[0m"
    echo "$message" >> "$LOG_FILE"
}

# 判断是否 root 用户
if [ $(id -u) -ne 0 ]; then
    logger "error" "########## 错误：此脚本必须以 root 身份运行！ ##########"
    exit 1
fi

# 环境检查
if which getenforce && [ $(getenforce) == "Enforcing" ]; then
    logger "info" "信息：关闭 SELINUX"
    setenforce 0
    sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
fi

# 定义安装函数
function install_docker() {
    local install_method="$1"

    if [ "$install_method" == "local" ]; then
        if [ -f docker-*.tar.gz ]; then
            logger "info" "信息：发现本地压缩包，进行解压安装"
            tar zxvf docker-*.tar.gz
            mv docker/docker.service /etc/systemd/system/docker.service
            cp docker/* /usr/bin
        else
            logger "warning" "警告：未找到本地压缩包，无法进行本地安装"
            return 1
        fi
    elif [ "$install_method" == "curl" ]; then
        logger "info" "信息：尝试通过 curl 安装 Docker"
        curl -fsSL https://get.docker.com | sh
    elif [ "$install_method" == "yum" ]; then
        logger "warning" "警告：尝试通过 Yum 安装 Docker"
        yum remove docker \
                      docker-client \
                      docker-client-latest \
                      docker-common \
                      docker-latest \
                      docker-latest-logrotate \
                      docker-logrotate \
                      docker-engine -y

        yum-config-manager \
                --add-repo \
                https://download.docker.com/linux/centos/docker-ce.repo

        yum install docker-ce  -y
    else
        logger "error" "错误：无效的安装方法"
        return 1
    fi

    systemctl daemon-reload
    systemctl enable docker
    systemctl start docker
    logger "success" "成功：安装 Docker 并启动服务（$install_method 方式）"
}

# 尝试本地安装
if install_docker "local"; then
    exit 0
fi

# 尝试 curl 安装
if install_docker "curl"; then
    exit 0
fi

# 尝试 yum 安装
install_docker "yum"

logger "info" "======================= 安装完成 ======================="